#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include <errno.h>

#define GPIO_EXPORT "/sys/class/gpio/export"
#define GPIO_UNEXPORT "/sys/class/gpio/unexport"
#define GPIO_DIRECTION "/sys/class/gpio/gpio%d/direction"
#define GPIO_VALUE "/sys/class/gpio/gpio%d/value"

// 注意：你需要根据实际的脉冲宽度和周期来调整下面的值
#define T_PW_SEC 0              // 脉冲宽度的秒部分
#define T_PW_NSEC 2000000       // 脉冲宽度的纳秒部分 (例如，1ms)
#define T_TT_SEC 0              // 总周期的秒部分
#define T_TT_NSEC 100000000     // 总周期的纳秒部分 (例如，100ms)

void gpio_setup(int gpio, const char *direction) {
    char path[35];
    int fd;

    // 导出GPIO
    fd = open(GPIO_EXPORT, O_WRONLY);
    if (fd == -1) {
        perror("Export failed");
        exit(EXIT_FAILURE);
    }
    dprintf(fd, "%d", gpio);
    close(fd);

    // 设置GPIO方向
    snprintf(path, sizeof(path), GPIO_DIRECTION, gpio);
    fd = open(path, O_WRONLY);
    if (fd == -1) {
        perror("Direction setup failed");
        exit(EXIT_FAILURE);
    }
    write(fd, direction, strlen(direction));
    close(fd);
}

void gpio_write(int gpio, int value) {
    char path[35];
    int fd;

    snprintf(path, sizeof(path), GPIO_VALUE, gpio);
    fd = open(path, O_WRONLY);
    if (fd == -1) {
        perror("Write to GPIO failed");
        exit(EXIT_FAILURE);
    }
    dprintf(fd, "%d", value);
    close(fd);
}

void precise_sleep(long sec, long nsec) {
    struct timespec req, rem;

    req.tv_sec = sec;
    req.tv_nsec = nsec;
    while (nanosleep(&req, &rem) && errno == EINTR) {
        req = rem;
    }
}

int main(int argc, char *argv[]) {
    int gpio = 118; // GPIO编号，需要根据实际情况修改

    gpio_setup(gpio, "out");

    while (1) {
        // 创建脉冲
        gpio_write(gpio, 1);
        precise_sleep(T_PW_SEC, T_PW_NSEC);
        gpio_write(gpio, 0);

        // 计算下一个脉冲前的延时
        precise_sleep(T_TT_SEC - T_PW_SEC, T_TT_NSEC - T_PW_NSEC);
    }

    return 0;
}

